<?php
// +----------------------------------------------------------------------
// | UKnowing [You Know] 简称 UK
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2021 https://www.uknowing.com
// +----------------------------------------------------------------------
// | UKnowing一款基于TP6开发的社交化知识付费问答系统、企业内部知识库系统，打造私有社交化问答、内部知识存储
// +----------------------------------------------------------------------
// | Author: UK团队 <devteam@uknowing.com>
// +----------------------------------------------------------------------

namespace app\member\backend;
use app\common\controller\Backend;
use app\common\model\UsersPowerGroup as UsersGroupModel;

class UsersPowerGroup extends Backend
{
	public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new UsersGroupModel();
        $this->table = 'users_power_group';
    }

    //用户组列表
    public function index()
    {
        $columns = [
            ['id','组ID'],
            ['group_icon','组标识','image'],
            ['min_power', '最小声望'],
            ['max_power', '最大声望'],
            ['power_factor','声望系数'],
            ['title', '组名称'],
            ['status', '状态', 'status', '0',['0' => '禁用','1' => '启用']],
            ['create_time', '创建时间','datetime'],
            ['update_time', '更新时间','datetime'],
        ];

        $search = [
            ['text', 'title', '组名称', 'LIKE'],
        ];

        if ($this->request->param('_list'))
        {
            // 排序规则
            $orderByColumn = $this->request->param('orderByColumn') ?? 'id';
            $isAsc = $this->request->param('isAsc') ?: 'ASC';
            $where = $this->makeBuilder->getWhere('uid',$search);
            // 排序处理
            return db($this->table)
                ->where($where)
                ->order([$orderByColumn => $isAsc,'create_time'=>'asc'])
                ->paginate([
                    'query'     => $this->request->get(),
                    'list_rows' => 15,
                ])
                ->toArray();
        }

        return $this->tableBuilder
            ->setUniqueId('id')
            ->addColumns($columns)
            ->setSearch($search)
            ->addColumn('right_button', '操作', 'btn')
            ->setPagination('false')
            ->addRightButtons([
                'edit',
                'delete',
                'permission'=>[
                    'type'          =>'permission',
                    'title'         => '权限管理',
                    'icon'          => 'fa fa-cogs',
                    'class'         => 'btn btn-success btn-xs uk-ajax-open',
                    'url'           => (string)url('permission',['id'=>'__id__']),
                    'href'          =>''
                ]
            ])
            ->addTopButtons(['add','delete'])
            ->fetch();
    }

	//添加用户组
	public function add()
    {
        if($this->request->isPost())
        {
            $data = $this->request->except(['file']);
            $permission = db('users_permission')->where('group_type','score')->column('name,value');
            foreach ($permission as $key=>$val)
            {
                $data['permission'][$val['name']]=$val['value'];
            }
            $data['permission'] = json_encode($data['permission'],JSON_UNESCAPED_UNICODE);

            $result = $this->model->create($data);
            if (!$result) {
                $this->error('添加失败');
            } else {
                $this->success('添加成功','index');
            }
        }

        return $this->formBuilder
            ->addText('title','组名称','填写组名称')
            ->addImage('group_icon','组标识','上传组标识')
            ->addText('min_power','最小声望','升级到该组最小声望')
            ->addText('max_power','最大声望','升级到该组最大声望')
            ->addText('power_factor','声望系数')
            ->addRadio('status','状态','是否启用',['0' => '禁用','1' => '启用'],1)
            ->fetch();
	}

    public function edit(string $id)
    {
        if ($this->request->isPost())
        {
            $data =$this->request->except(['file']);
            $result = $this->model->update($data);
            if ($result) {
                $this->success('修改成功', 'index');
            } else {
                $this->error('修改失败');
            }
        }

        $info =$this->model->find($id)->toArray();
        // 获取字段信息
        return $this->formBuilder
            ->addHidden('id',$info['id'])
            ->addText('title','组名称','填写组名称',$info['title'])
            ->addImage('group_icon','组标识','上传组标识',$info['group_icon'])
            ->addText('min_power','最小声望','升级到该组最小声望',$info['min_power'])
            ->addText('max_power','最大声望','升级到该组最大声望',$info['max_power'])
            ->addText('power_factor','声望系数','',$info['power_factor'])
            ->addRadio('status','状态','是否启用',['0' => '禁用','1' => '启用'],$info['status'])
            ->fetch();
    }

	public function permission($id=0)
	{
        if ($this->request->isPost())
        {
            if ($data=$this->request->post()) {
                foreach ($data as $k => $v) {

                    if (is_array($v)) {
                        if(isset($v['key']) && isset($v['value']))
                        {
                            $value = [];
                            foreach ($v['key'] as $k1=>$v1)
                            {
                                $value[$v1] = $v['value'][$k1];
                            }
                            $data[$k] = $value;
                        }
                    }
                }
                $result=UsersGroupModel::update(['permission'=>json_encode($data,JSON_UNESCAPED_UNICODE)],['id'=>$id]);
                if ($result) {
                    $this->success('修改成功');
                } else {
                    $this->error('修改失败');
                }
            }
        }

        $permission = $this->model->where(['id'=>$id])->value('permission');
        $permission = json_decode($permission,true);
        $list = db('users_permission')->where('group_type','power')->column('type,name,title,tips,option,value');

        $columns = [];
        foreach ($list as $key=>$val)
        {
            $list[$key]['option'] = json_decode($val['option'],true);
            if(!in_array($val['type'],['radio','checkbox','select','array']))
            {
                unset($list[$key]['option']);
            }
            if(isset($permission[$val['name']]))
            {
                $list[$key]['value'] = $permission[$val['name']];
            }
        }
        foreach ($list as $key=>$val)
        {
            $columns[$key] = array_values($val);
        }

        // 构建页面
        return $this->formBuilder
            ->addFormItems($columns)
            ->setFormUrl((string)url('permission',['id'=>$id]))
            ->fetch();
	}
}